//用户小仓库
import { defineStore } from "pinia";
//引入路由
import { anyRoutes } from "@/router/routes";
//引入路由器
import router from "@/router";
import setting from "../../setting";
// 引入获取路由接口
import { getRoutes,getRoute,deleteRoute,updateRoute,addRoute } from '@/api/test/index'
import Layout from '@/layout/index.vue'
import { maToSa } from '@/utils/array'
import { confirmBox,msgBox } from "@/utils/dialog";
import { defineAsyncComponent } from "vue";
// 模拟权限名单
let permiList = [
  '/admin',
  '/admin/addRoute',
  '/admin/AllRoutes',
  '/admin/editroute'
]
// 隐藏路由，不在菜单显示，但可以访问
let hideList = [
  '/admin/editroute',
]

let useRouteStore = defineStore("Routes", {
  state: () => {
    return {
      // 动态路由列表
      routes: null, 
      // 模拟按钮权限列表
      btnPermiList: [
        'admin:routes:add',
        'admin:routes:edit',
        'admin:routes:delete'
      ]
    };
  },
  actions: {
    // 获取指定路由
    async getRoute(id) {
      let routesResult = await getRoute(id)
      return JSON.parse(routesResult.data)[0]
    },
    // 获取全部路由
    async getRoutes(toSa = false) {
      let routesResult = await getRoutes()
      if(toSa){
        return maToSa(JSON.parse(routesResult.data))
      }else{
        return JSON.parse(routesResult.data)
      }
    },
    // 添加路由(添加到数据库)
    async addRoute(route){
      let result = await addRoute(route)
      return result
    },
    // 添加路由(添加到Vue，而不是数据库)
    async addRoutes() {
      let routes = []
      let asyncRoutes = []
      let routesResult = await getRoutes()

      if(routesResult.code == 200){
        let data = JSON.parse(routesResult.data)
        asyncRoutes = JSON.parse(JSON.stringify(data))

        let password = localStorage.getItem('password')
        if(password != setting.password){
          // 无权限，过滤掉没有权限的路由
          asyncRoutes = filterRoutes(JSON.parse(JSON.stringify(asyncRoutes)),permiList)
        }
        // 将路由转换为组件对象
        asyncRoutes = filterAsyncRouter(asyncRoutes)
        // 合并任意路由
        routes = [...asyncRoutes, anyRoutes]
        // 开始过滤隐藏路由
        // let showRoutes = filterRoutes(JSON.parse(JSON.stringify(asyncRoutes)),hideList)
        // 将最终显示路由赋值给state
        // this.routes = showRoutes

        this.routes = asyncRoutes
        return routes
      }else{
        throw new Error('路由获取失败');
      }
    },
    // 编辑路由
    async updateRoute(id,route){
      let result = await updateRoute(id,route)
      return result
    },
    // 删除路由
    deleteRoute(route,callback){
      deleteRoute(route.id).then(r=>{
        msgBox('删除成功')
        router.removeRoute(route.name)
        callback()
        // 这里还可以做一个操作，删除state中对应的路由数据
        console.log(r)
      }).catch(e=>{
        msgBox('删除失败','danger')
        console.log(e)
      })
    }
  },
  getters: {},
});

function filterRoutes(routes,filterArr) {
  return routes.filter(item => {
    if (item.children) {
      item.children = filterRoutes(item.children,filterArr);
    }
    return filterArr.indexOf(item.path) === -1;
  });
}

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  return asyncRouterMap.filter(route => {
    if (type && route.children) {
      route.children = filterChildren(route.children)
    }
    if (route.component) {
      // Layout ParentView 组件特殊处理
      if (route.component === 'Layout' || route.component === 'layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children, route, type)
    } else {
      delete route['children']
      delete route['redirect']
    }
    return true
  })
}

const loadView = (view) => {
  const modules = import.meta.glob('../../views/**/*.vue');
  // 这里用import直接导入生产环境下会出问题，浏览器中js会去使用import导入vue文件，导致生产环境下无法正常运行
  // 上面的结果是一个对象，获取所以views下的vue文件并import导入，相当于
  // const modules ={
  //     "../views/daily/index.vue": () => import("/src/views/daily/index.vue")
  // }
  return modules[`../../views/${view}`]
}

export default useRouteStore;
